<?php
namespace App\Controllers\Admin;

use App\Components\Admin\ResponseHelper;
use App\Components\Admin\Router;
use App\Components\Twig\Twig;
use App\Helpers\RequestHelper;
use App\Helpers\UrlHelper;
use App\Models\System\SystemMenu;
use App\Models\System\SystemUser;
use Exception;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;

class IndexController
{
    public function index(Request $request, Response $response)
    {
        $userId = SystemUser::getIdByToken();
        if ($userId <= 0) {
            return UrlHelper::redirectUrl($response, Router::URL_PREFIX . '/index/login');
        }

        $menuRs = SystemMenu::userMenu($userId);
        $url = $this->getFirstUrl($menuRs);
        if ($url == '') {
            throw new Exception('无管理菜单入口');
        }

        return UrlHelper::redirectUrl($response, $url);
    }

    private function getFirstUrl(array $menu): string
    {
        $url = '';
        foreach ($menu as $v) {
            if (isset($v['children'])) {
                $url = $this->getFirstUrl($v['children']);
                if ($url != '') {
                    break;
                }
            } else {
                if (!isset($v['node']) || $v['node'] == '#') {
                    continue;
                }
                $url = $v['node'] . ($v['parameter'] == '' ? '' : '?' . $v['parameter']);
                break;
            }
        }

        return $url;
    }

    public function login(Request $request, Response $response)
    {
        if ($request->getMethod() == 'POST') {
            $params = $request->getParsedBody();
            $params = array_filter($params);
            if (!isset($params['username']) || !isset($params['password'])) {
                return ResponseHelper::error($response, '请输入账号密码');
            }

            $infoRs = SystemUser::select('id', 'password', 'status')
                ->where('username', $params['username'])->first();
            if (!isset($infoRs->id)) {
                return ResponseHelper::error($response, '账号或密码错误');
            }
            if ($infoRs->status != 1) {
                return ResponseHelper::error($response, '账号已被禁用');
            }
            if (password_verify($params['password'], $infoRs->password) !== true) {
                return ResponseHelper::error($response, '账号或密码错误');
            }

            $updateData = [
                'logged_at' => date('Y-m-d H:i:s'),
                'logged_ip' => ip2long(RequestHelper::getClientIpAddress($request)),
            ];
            $token = SystemUser::generateToken($infoRs->id);
            if ($token == '') {
                return ResponseHelper::error($response, '登录TOKEN生成错误');
            }
            if (isset($params['remember']) && $params['remember'] == 'on') {
                $updateData['token'] = $token;
            }
            $updateRs = SystemUser::where('id', $infoRs->id)->update($updateData);
            if ($updateRs != 1) {
                return ResponseHelper::error($response, '登录信息更新错误');
            }

            if (isset($params['remember']) && $params['remember'] == 'on') {
                SystemUser::saveToken($infoRs->id, $token, true);
            } else {
                SystemUser::saveToken($infoRs->id, $token, false);
            }

            return ResponseHelper::success($response, [
                'url' => $params['redirect'] ?? Router::URL_PREFIX . '/index/index',
            ]);
        }

        $params = $request->getQueryParams();
        $params = array_filter($params);

        $view = Twig::fromRequest($request);
        $response->getBody()->write($view->fetch('admin/index/login.html', [
            'param' => $params,
        ]));
        return $response;
    }
}
